package logic

import (
	"gameserver/gcommon"
	"gameserver/messages"
	"gameserver/server"

	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/logger"
	"gitee.com/night-tc/gobige/msgdef/protomsg"
)

type GatewayProc struct {
	player *Player
}

// ReLoadPlayerSrv Gateway通知的玩家断线重连
func (this *GatewayProc) MsgProc_ReLoadPlayerSrv(msg *messages.ReLoadPlayerSrv) {
	logger.Debugf(server.LogKey_LoginFlow, "玩家重连 player:%d", this.player.GetEntityID())
	this.player.ReLoadPlayer(msg.SessState)
}

// PlayerOfflineSrv Gateway通知的玩家下线
func (this *GatewayProc) MsgProc_PlayerOfflineSrv(msg *messages.PlayerOfflineSrv) {
	// 处理断线逻辑，可能需要通知别人，需要结束一些在线计时等逻辑
	logger.Debugf(server.LogKey_LoginFlow, "玩家链接断开 player:%d", this.player.GetEntityID())
}

func (this *GatewayProc) MsgProc_LogoutPlayerSrv(msg *messages.LogoutPlayerSrv) {
	/*
	   运行离线逻辑
	*/
	logger.Debugf(server.LogKey_LoginFlow, "玩家离线过程，卸载玩家数据 player:%d", this.player.GetEntityID())
	err := this.player.DestroyEntityByStype(global.ServerTypeGateway, func(msgret *protomsg.RouteMsgSrvRet, err error) {
		_ = this.player.GetEntities().DestroyEntity(this.player.GetEntityID())
	})
	if err != nil {
		_ = this.player.GetEntities().DestroyEntity(this.player.GetEntityID())
	}
}

// Srv_LogoutPlayerSrv 处理服务器发过来的顶号请求
// 这个消息是服务器发过来的,需要处理掉线逻辑
func (this *GatewayProc) Srv_LogoutPlayerSrv(req *protomsg.RouteMsgSrvReq, msg *messages.LogoutPlayerSrv) error {
	/*
	   运行离线逻辑
	*/
	logger.Debugf(server.LogKey_LoginFlow, "玩家被顶号 player:%d", this.player.GetEntityID())
	_ = this.player.Post(global.ServerTypeClient, &messages.KickPlayerNtf{
		RetCode: gcommon.RETMSG_User_Logged_account,
	})
	err := this.player.DestroyEntityByStype(global.ServerTypeGateway, func(msgret *protomsg.RouteMsgSrvRet, err error) {
		_ = this.player.GetEntities().DestroyEntity(this.player.GetEntityID())
	})
	if err != nil {
		_ = this.player.GetEntities().DestroyEntity(this.player.GetEntityID())
	}
	return gcommon.Err_success
}
